﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public class JsonHelper
    {
        private static JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
        public static T Deserialize<T>(string json)
        {
            try
            {
                if (string.IsNullOrEmpty(json))
                {
                    return default(T);
                }
                JsonReader reader = new JsonTextReader(new StringReader(json));
                return serializer.Deserialize<T>(reader);
            }
            catch (Exception ex)
            {
                LogWriter.WriteError(ex, "JSON反序列化指定对象异常-Json：" + json);
                return default(T);
            }
        }

        public static string Serialize(object obj)
        {
            try
            {
                StringWriter sw = new StringWriter();
                JsonWriter writer = new JsonTextWriter(sw);
                serializer.Serialize(writer, obj);
                return sw.ToString();
            }
            catch (Exception ex)
            {
                LogWriter.WriteError(ex, "指定对象序列化JSON异常");
                return "";
            }
        }
    }
}
